package it.asvp.asvp_portal.data.dao.impl;


import it.asvp.asvp_portal.data.dao.MemberAccountDao;
import it.asvp.asvp_portal.data.entity.member.Member;
import it.asvp.asvp_portal.data.entity.member.MemberAccount;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class MemberAccountDaoImpl implements MemberAccountDao{

	private static final Log log = LogFactory.getLog(MemberAccountDaoImpl.class);

	@Autowired
	SessionFactory sessionFactory;

	public Long persist(MemberAccount transientInstance) {
		log.debug("persisting MemberAccount instance");
		Long id;
		try {
			id=(Long) sessionFactory.getCurrentSession().save(transientInstance);
			log.debug("persist successful");
		} catch (RuntimeException re) {
			log.error("persist failed", re);
			throw re;
		}
		return id;
	}

	public void delete(MemberAccount persistentInstance) {
		log.debug("deleting MemberAccount instance");
		try {
			sessionFactory.getCurrentSession().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public MemberAccount merge(MemberAccount detachedInstance) {
		log.debug("merging MemberAccount instance");
		try {
			MemberAccount result = (MemberAccount) sessionFactory.getCurrentSession().merge(detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

    public MemberAccount findById(java.lang.Long id) {
		
		Criteria cr=sessionFactory.getCurrentSession().createCriteria(MemberAccount.class);
		cr.add(Restrictions.eq("id", id));
		MemberAccount mA = (MemberAccount)cr.uniqueResult();
		return mA;
	}
    
    public MemberAccount findByLogin(String login){
    	
		Criteria cr=sessionFactory.getCurrentSession().createCriteria(MemberAccount.class);
		cr.add(Restrictions.eq("login", login));
		MemberAccount mA = (MemberAccount)cr.uniqueResult();
		return mA;
    }
    
    public MemberAccount findBy(String login,String password){
    	
    	Criteria cr=sessionFactory.getCurrentSession().createCriteria(MemberAccount.class);
    	cr.add(Restrictions.eq("login", login));
		cr.add(Restrictions.eq("password", password));
		MemberAccount mA = (MemberAccount)cr.uniqueResult();
		return mA;
    }
    
    public MemberAccount findByMember(Member member) {
		
		Criteria cr=sessionFactory.getCurrentSession().createCriteria(MemberAccount.class);
		cr.add(Restrictions.eq("member", member));
		MemberAccount mA = (MemberAccount)cr.uniqueResult();
		return mA;
	}
}
